#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <climits>

using namespace std;


// 课程表
class Solution
{
public:
    bool canFinish(int n, vector<vector<int>>& prerequisites)
    {
        // 邻接表--保存出度
        unordered_map<int,vector<int>> edges;
        // 保存入度
        vector<int> in(n);

        for(auto& e : prerequisites)
        {
            // b -> a
            int a = e[0],b = e[1];
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        for(int i = 0;i < n;i++)
        {
            if(in[i] == 0)
                q.push(i);
        }

        // 拓扑排序
        while(q.size())
        {
            int t = q.front();
            q.pop();
            for(auto x : edges[t])
            {
                if(--in[x] == 0)
                {
                    q.push(x);
                }
            }
        }

        for(auto x : in)
        {
            if(x)
                return false;
        }
        return true;
    }
};

// 课程表II
class Solution
{
public:
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites)
    {
        unordered_map<int,vector<int>> edges;
        vector<int> in(n),ans;

        for(auto& e : prerequisites)
        {
            //b -> a
            int a = e[0],b = e[1];
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        for(int i = 0;i < n;i++)
        {
            if(in[i] == 0) q.push(i);
        }

        while(q.size())
        {
            int t = q.front();
            q.pop();
            ans.push_back(t);
            for(auto& x : edges[t])
            {
                if(--in[x] == 0) q.push(x);
            }
        }

        return ans.size() == n ? ans : std::vector<int>();
    }
};